package com.example.attrimirror.ui.combine;

import android.content.Context;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.attrimirror.R;
import com.example.attrimirror.databinding.ItemCombineRecipeBinding;
import com.example.attrimirror.model.Item;
import com.example.attrimirror.model.Attribute;
import com.example.attrimirror.utils.CollectionManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Locale;

public class CombineRecipeAdapter extends RecyclerView.Adapter<CombineRecipeAdapter.ViewHolder> {
    private final Context context;
    private final CollectionManager collectionManager;

    public CombineRecipeAdapter(Context context) {
        this.context = context;
        this.collectionManager = new CollectionManager(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemCombineRecipeBinding binding = ItemCombineRecipeBinding.inflate(
                LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // 清空之前的视图
        holder.ingredientsLayout.removeAllViews();
        
        // 创建两列布局
        LinearLayout rowLayout = null;
        String[] days = {"mon", "tue", "wed", "thu", "fri", "sat", "sun"};
        
        for (int i = 0; i < days.length; i++) {
            // 每两个物品创建一行
            if (i % 2 == 0) {
                rowLayout = new LinearLayout(context);
                rowLayout.setOrientation(LinearLayout.HORIZONTAL);
                rowLayout.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ));
                holder.ingredientsLayout.addView(rowLayout);
            }
            
            String itemId = "checkin." + days[i];
            Item item = collectionManager.getItem(itemId);
            addItemView(rowLayout, item, 1);
        }
        
        // 更新补签珠数量显示
        Item lateCheckToken = collectionManager.getItem("latechecktoken");
        if (lateCheckToken != null) {
            holder.lateCheckCount.setText(String.format(Locale.getDefault(), "当前补签珠：%d", lateCheckToken.getNumber()));
        }
        
        // 设置合成按钮
        boolean canCombine = checkCanCombine();
        holder.combineButton.setEnabled(canCombine);
        holder.combineButton.setAlpha(canCombine ? 1.0f : 0.5f);
        
        holder.combineButton.setOnClickListener(v -> {
            if (checkCanCombine()) {
                try {
                    // 扣除七个签到勋章
                    for (String day : days) {
                        collectionManager.updateItemNumber("checkin." + day, -1);
                    }
                    
                    // 添加补签珠
                    collectionManager.updateItemNumber("latechecktoken", 2);
                    
                    // 读取属性文件
                    File dataDir = new File(Environment.getExternalStorageDirectory(), "AttriMirror/data");
                    File attributeFile = new File(dataDir, "attribute.json");
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<Attribute>>(){}.getType();
                    List<Attribute> attributes;
                    
                    try (FileReader reader = new FileReader(attributeFile)) {
                        attributes = gson.fromJson(reader, type);
                    }
                    
                    // 更新秩序属性
                    for (Attribute attr : attributes) {
                        if ("attribute.order".equals(attr.getId())) {
                            attr.setExperience(attr.getExperience() + 3);
                            break;
                        }
                    }
                    
                    // 保存更新后的属性数据
                    try (FileWriter writer = new FileWriter(attributeFile)) {
                        gson.toJson(attributes, writer);
                    }
                    
                    // 保存仓库数据
                    collectionManager.saveData();
                    
                    // 更新显示
                    notifyItemRangeChanged(0, getItemCount());
                    Toast.makeText(context, "合成成功！秩序+3，补签珠+2", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(context, "更新失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(context, "材料不足！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return 1;
    }

    private boolean checkCanCombine() {
        String[] days = {"mon", "tue", "wed", "thu", "fri", "sat", "sun"};
        for (String day : days) {
            Item item = collectionManager.getItem("checkin." + day);
            if (item == null || item.getNumber() < 1) {
                return false;
            }
        }
        return true;
    }

    private void addItemView(LinearLayout container, Item item, int amount) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.item_recipe_material, container, false);
        
        ImageView iconView = itemView.findViewById(R.id.item_icon);
        TextView countView = itemView.findViewById(R.id.item_count);
        
        if (item != null) {
            // 设置图标
            int resourceId = context.getResources().getIdentifier(
                item.getIcon().replace(".png", ""),
                "drawable",
                context.getPackageName()
            );
            if (resourceId != 0) {
                iconView.setImageResource(resourceId);
            }
            
            // 设置数量
            String countText = String.format(Locale.getDefault(), "%d/%d", item.getNumber(), amount);
            countView.setText(countText);
        }
        
        // 设置权重，使两列宽度相等
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            0,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            1
        );
        itemView.setLayoutParams(params);
        
        container.addView(itemView);
    }

    protected static class ViewHolder extends RecyclerView.ViewHolder {
        final LinearLayout ingredientsLayout;
        final Button combineButton;
        final TextView lateCheckCount;

        ViewHolder(ItemCombineRecipeBinding binding) {
            super(binding.getRoot());
            ingredientsLayout = binding.recipeIngredients;
            combineButton = binding.btnCombine;
            lateCheckCount = binding.lateCheckCount;
        }
    }
} 